import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Form, Input, InputNumber, message, Modal, Table } from 'antd';
import React, { useRef, useState } from 'react';
import type { CategoryItem } from '../../services/productCategory';
import {
  addMainCategory,
  deleteMainCategory,
  qryMainCategoryDetail,
  qryMainCategoryListPage,
  updateMainCategory,
} from '../../services/productCategory';

const ProductCategoryPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState<string>();
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');

  // 子类目相关状态
  const [childCategoryModalVisible, setChildCategoryModalVisible] =
    useState(false);
  const [childCategoryForm] = Form.useForm();
  const [currentChildCategoryIndex, setCurrentChildCategoryIndex] =
    useState<number>(-1);
  const [childCategoryModalType, setChildCategoryModalType] = useState<
    'add' | 'edit'
  >('add');

  const handleAdd = () => {
    setModalType('add');
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = async (id: string) => {
    setModalType('edit');
    setCurrentId(id);
    try {
      const detail = await qryMainCategoryDetail({ categoryId: id });
      form.setFieldsValue(detail);
      setModalVisible(true);
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除该产品父类目吗？',
      onOk: async () => {
        await deleteMainCategory({ categoryId: id });
        message.success('删除成功');
        actionRef.current?.reload();
      },
    });
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (modalType === 'add') {
        await addMainCategory(values);
        message.success('添加成功');
      } else {
        await updateMainCategory({ ...values, categoryId: currentId });
        message.success('更新成功');
      }
      setModalVisible(false);
      return true;
    } catch (error) {
      message.error('操作失败');
      return false;
    }
  };

  // 子类目管理函数
  const handleAddChildCategory = () => {
    setChildCategoryModalType('add');
    childCategoryForm.resetFields();
    setCurrentChildCategoryIndex(-1);
    setChildCategoryModalVisible(true);
  };

  const handleEditChildCategory = (index: number) => {
    const childCategoryList = form.getFieldValue('childCategoryList') || [];
    const childCategory = childCategoryList[index];
    if (childCategory) {
      setChildCategoryModalType('edit');
      setCurrentChildCategoryIndex(index);
      childCategoryForm.setFieldsValue(childCategory);
      setChildCategoryModalVisible(true);
    }
  };

  const handleDeleteChildCategory = (index: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除该子类目吗？',
      onOk: () => {
        const childCategoryList = form.getFieldValue('childCategoryList') || [];
        const newList = childCategoryList.filter(
          (_: any, i: number) => i !== index,
        );
        form.setFieldValue('childCategoryList', newList);
        message.success('删除成功');
      },
    });
  };

  const handleChildCategorySubmit = async () => {
    try {
      const values = await childCategoryForm.validateFields();
      const childCategoryList = form.getFieldValue('childCategoryList') || [];

      if (childCategoryModalType === 'add') {
        const newChildCategory = {
          categoryId: '', // 为空，实际应该由后端生成
          categoryName: values.categoryName,
        };
        form.setFieldValue('childCategoryList', [
          ...childCategoryList,
          newChildCategory,
        ]);
        message.success('添加子类目成功');
      } else {
        const newList = [...childCategoryList];
        newList[currentChildCategoryIndex] = {
          ...newList[currentChildCategoryIndex],
          categoryName: values.categoryName,
        };
        form.setFieldValue('childCategoryList', newList);
        message.success('更新子类目成功');
      }

      setChildCategoryModalVisible(false);
      return true;
    } catch (error) {
      message.error('操作失败');
      return false;
    }
  };

  // 子类目表格列配置
  const childCategoryColumns = [
    {
      title: '类目名称',
      dataIndex: 'categoryName',
      key: 'categoryName',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, __: any, index: number) => [
        <a key="edit" onClick={() => handleEditChildCategory(index)}>
          编辑
        </a>,
        <span key="divider" style={{ margin: '0 8px', color: '#d9d9d9' }}>
          |
        </span>,
        <a key="delete" onClick={() => handleDeleteChildCategory(index)}>
          删除
        </a>,
      ],
    },
  ];

  const columns: ProColumns<CategoryItem>[] = [
    {
      title: '排序序号',
      dataIndex: 'serNum',
      key: 'serNum',
      valueType: 'digit',
      hideInSearch: true,
    },
    {
      title: '父类目编号',
      dataIndex: 'categoryId',
      key: 'categoryId',
      hideInSearch: true,
    },
    {
      title: '父类目名称',
      dataIndex: 'categoryName',
      key: 'categoryName',
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      render: (_, record) => [
        <a key="edit" onClick={() => handleEdit(record.categoryId)}>
          编辑
        </a>,
        <a key="delete" onClick={() => handleDelete(record.categoryId)}>
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<CategoryItem>
        actionRef={actionRef}
        rowKey="categoryId"
        columns={columns}
        request={async (params) => {
          const { current, pageSize, categoryName } = params;
          console.log(params);
          const result = await qryMainCategoryListPage({
            pageIndex: current,
            pageSize,
            param: {
              categoryName,
            },
          });
          return {
            data: result.list,
            total: result.total,
            success: true,
          };
        }}
        toolBarRender={() => [
          <Button type="primary" key="add" onClick={handleAdd}>
            新增产品父类目
          </Button>,
        ]}
      />

      <Modal
        title={modalType === 'add' ? '新增产品父类目' : '编辑产品父类目'}
        open={modalVisible}
        width={800}
        onOk={async () => {
          const success = await handleSubmit();
          if (success) {
            setModalVisible(false);
            actionRef.current?.reload();
          }
        }}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="categoryName"
            label="父类目名称"
            rules={[{ required: true, message: '请输入父类目名称' }]}
          >
            <Input placeholder="请输入父类目名称" />
          </Form.Item>
          <Form.Item
            name="serNum"
            label="排序序号"
            rules={[{ required: true, message: '请输入排序序号' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入排序序号"
            />
          </Form.Item>

          {/* 子类目列表 */}
          <Form.Item name="childCategoryList" label="子类目列表">
            <Form.Item
              shouldUpdate={(prevValues, currentValues) =>
                prevValues.childCategoryList !== currentValues.childCategoryList
              }
            >
              {() => (
                <div>
                  <div style={{ marginBottom: 8 }}>
                    <Button
                      type="primary"
                      size="small"
                      onClick={handleAddChildCategory}
                    >
                      新增子类目
                    </Button>
                  </div>
                  <Table
                    columns={childCategoryColumns}
                    dataSource={form.getFieldValue('childCategoryList') || []}
                    pagination={false}
                    size="small"
                    bordered
                    locale={{
                      emptyText: '暂无子类目数据',
                    }}
                  />
                </div>
              )}
            </Form.Item>
          </Form.Item>
        </Form>
      </Modal>

      {/* 子类目管理弹窗 */}
      <Modal
        title={childCategoryModalType === 'add' ? '新增子类目' : '编辑子类目'}
        open={childCategoryModalVisible}
        onOk={async () => {
          const success = await handleChildCategorySubmit();
          if (success) {
            setChildCategoryModalVisible(false);
          }
        }}
        onCancel={() => setChildCategoryModalVisible(false)}
      >
        <Form form={childCategoryForm} layout="vertical">
          <Form.Item
            name="categoryName"
            label="子类目名称"
            rules={[{ required: true, message: '请输入子类目名称' }]}
          >
            <Input placeholder="请输入子类目名称" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default ProductCategoryPage;
